<?php defined('BASEPATH') OR exit('No direct script access allowed');

class sitetemplate extends wsBackend
{
    public function index()
    {
        $data = array();

        $this->tpl->meta ['title'] = '模版管理 - ' . $this->config->item('site_name');
        $this->tpl->meta ['description'] = '';
        $this->tpl->meta ['keywords'] = '';

        $tp = FCPATH . $this->template_path();
        $data['current_theme'] = basename($tp);
        $data['theme_location'] = FCPATH . 'themes';
        $this->load->helper('file');
        $data['available_themes'] = $this->is_this_dir($data['theme_location']);

        if (isset($_POST['template']) && in_array($_POST['template'], $data['available_themes'])) {
            $this->db->update('setting', array('setting_value' => $this->input->post('template')), array('setting_key' => 'frontendTheme'));
            $this->session->set_flashdata('SUCCESS', '模版更新完成');
            $this->load->library('language');
            $this->language->save_config();
            redirect(admin_url('sitetemplate'));
        }

        $this->tpl->contents [] = $this->tpl->fetch('contents/sitetemplate', $data);
        $this->tpl->render();
    }

    private function is_this_dir($path)
    {
        $dir = array_diff(scandir($path), array('..', '.'));
        if (empty($dir))
            return false;
        $a = array();
        foreach ($dir as $v)
            if (is_dir($path . "/" . $v))
                $a[$v] = $v;
        return $a;
    }
}
